package utils;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.highgui.Highgui;

public class ImageUtils {

	public static BufferedImage createBufferedImage (Mat image) {
		
		byte[] byteArray = matToByteArray(image);
		BufferedImage bufImage = null;

		try {

			InputStream in = new ByteArrayInputStream(byteArray);
			bufImage = ImageIO.read(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  bufImage;

	}

	public static byte[] matToByteArray (Mat image) {

		MatOfByte matOfByte = new MatOfByte();
		Highgui.imencode(".jpg", image, matOfByte); 
		return matOfByte.toArray();
	}

	public static void showImage (Mat image) {

		JFrame frame = new JFrame();
		final BufferedImage bufIm = createBufferedImage(image);
		frame.setSize(bufIm.getWidth(), bufIm.getHeight());
		frame.setContentPane(new JPanel() {
			private static final long serialVersionUID = 1L;
			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				g.drawImage(bufIm , 0, 0, null);
			}
		});
		frame.setVisible(true);

	}

	public static byte[] imageToByteArray (ImageIcon i) {
		byte[] bytes = null;
		if (i!= null) {
			try {
				BufferedImage bufferedImage = new BufferedImage(i.getIconWidth(), i.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
				Graphics2D g2 = bufferedImage.createGraphics();
				g2.drawImage(i.getImage(), 0, 0, null);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(bufferedImage, "png", baos);
				bytes = baos.toByteArray();
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bytes;
	}

}
